"""目录采集对话框模块

作者: Guoyou Sun (孙国佑)
网站: http://sunguoyou.lamost.org/
版本: 1.0

版权所有 © 2025-2030 Guoyou Sun (孙国佑)
"""

import os
from PyQt5.QtCore import Qt, QDateTime
from PyQt5.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QLabel, 
                             QListWidget, QAbstractItemView, QPushButton, 
                             QDialogButtonBox, QSplitter, QWidget, QListWidgetItem, QMessageBox)

class CatalogCollectionDialog(QDialog):
    """目录采集对话框，用于选择要采集的年份和月份"""
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("目录采集设置")
        self.resize(500, 400)
        self.selected_months = {}  # 存储选中的月份 {year: [month1, month2, ...]}
        self.parent = parent  # 保存父窗口引用，用于访问配置
        
        self.create_widgets()
        self.load_years()
        self.deselect_all_btn.setEnabled(False)  # 初始禁用取消全选按钮
        
        # 如果配置中有上次选择的年份，则选中它
        if parent and hasattr(parent, 'config') and parent.config.has_section("Catalog") and "last_selected_year" in parent.config["Catalog"]:
            last_year = parent.config["Catalog"]["last_selected_year"]
            # 查找并选中上次选择的年份
            for i in range(self.year_list.count()):
                if self.year_list.item(i).text() == last_year:
                    self.year_list.setCurrentRow(i)
                    break
    
    def create_widgets(self):
        layout = QVBoxLayout(self)
        
        # 说明标签
        info_label = QLabel("请选择要采集的年份和月份：")
        layout.addWidget(info_label)
        
        # 创建分割器
        splitter = QSplitter(Qt.Horizontal)
        layout.addWidget(splitter)
        
        # 左侧年份列表
        year_widget = QWidget()
        year_layout = QVBoxLayout(year_widget)
        year_label = QLabel("年份")
        year_layout.addWidget(year_label)
        self.year_list = QListWidget()
        self.year_list.setSelectionMode(QAbstractItemView.SingleSelection)
        self.year_list.currentItemChanged.connect(self.on_year_selected)
        year_layout.addWidget(self.year_list)
        splitter.addWidget(year_widget)
        
        # 右侧月份列表
        month_widget = QWidget()
        month_layout = QVBoxLayout(month_widget)
        month_label = QLabel("月份")
        month_layout.addWidget(month_label)
        self.month_list = QListWidget()
        self.month_list.setSelectionMode(QAbstractItemView.MultiSelection)
        self.month_list.itemSelectionChanged.connect(self.on_month_selection_changed)
        month_layout.addWidget(self.month_list)
        splitter.addWidget(month_widget)
        
        # 全选/取消全选按钮
        select_buttons = QHBoxLayout()
        self.select_all_btn = QPushButton("全选")
        self.select_all_btn.clicked.connect(self.select_all_months)
        self.deselect_all_btn = QPushButton("取消全选")
        self.deselect_all_btn.clicked.connect(self.deselect_all_months)
        select_buttons.addWidget(self.select_all_btn)
        select_buttons.addWidget(self.deselect_all_btn)
        month_layout.addLayout(select_buttons)
        
        # 底部按钮
        button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        self.ok_button = button_box.button(QDialogButtonBox.Ok)
        self.ok_button.setEnabled(False)
        button_box.accepted.connect(self.accept)
        button_box.rejected.connect(self.reject)
        layout.addWidget(button_box)
    
    def load_years(self):
        """加载年份列表"""
        # 获取当前年份
        current_date = QDateTime.currentDateTime().date()
        current_year = current_date.year()
        
        # 添加2020-2030年的年份
        years = list(range(2020, 2031))  # 包含2026-2030年
        
        # 按照降序排列年份（最近的年份在前）
        years.sort(reverse=True)
        
        for year in years:
            item = QListWidgetItem(str(year))
            self.year_list.addItem(item)
            self.selected_months[str(year)] = []  # 初始化该年份的选中月份列表
        
        # 默认选中第一个年份
        if self.year_list.count() > 0:
            self.year_list.setCurrentRow(0)
            # 初始化时禁用确认按钮
            self.ok_button.setEnabled(False)
    
    def on_year_selected(self, current, previous):
        """当选择年份时，加载对应的月份列表"""
        if not current:
            return
            
        self.month_list.clear()
        year = current.text()
        
        # 加载1-12月
        for month in range(1, 13):
            month_str = f"{month:02d}"
            item = QListWidgetItem(month_str)
            self.month_list.addItem(item)
            
            # 如果该月份已被选中，则设置为选中状态
            if month_str in self.selected_months.get(year, []):
                item.setSelected(True)
    
    def on_month_selection_changed(self):
        """当月份选择变化时，更新选中的月份列表"""
        current_year = self.year_list.currentItem().text()
        selected_months = []
        
        for i in range(self.month_list.count()):
            item = self.month_list.item(i)
            if item.isSelected():
                selected_months.append(item.text())
        
        self.selected_months[current_year] = selected_months
        
        # 控制按钮状态
        has_selection = len(selected_months) > 0
        self.deselect_all_btn.setEnabled(has_selection)
        self.ok_button.setEnabled(has_selection)
    
    def select_all_months(self):
        """选择所有月份"""
        for i in range(self.month_list.count()):
            self.month_list.item(i).setSelected(True)
    
    def deselect_all_months(self):
        """取消选择所有月份"""
        for i in range(self.month_list.count()):
            self.month_list.item(i).setSelected(False)
    
    def get_selected_months(self):
        """获取所有选中的年份和月份"""
        result = {}
        for year, months in self.selected_months.items():
            if months:  # 只返回有选中月份的年份
                result[year] = months
        return result
    
    def accept(self):
        """确认选择，保存选中的月份"""
        # 有效性验证：至少选择一个月份
        if not any(self.get_selected_months().values()):
            QMessageBox.warning(self, "警告", "请至少选择一个月份！")
            return
            
        # 获取当前选中的年份和月份
        if self.year_list.currentItem():
            year = self.year_list.currentItem().text()
            
            # 保存到配置中
            if self.parent and hasattr(self.parent, 'config'):
                if not self.parent.config.has_section("Catalog"):
                    self.parent.config.add_section("Catalog")
                self.parent.config["Catalog"]["last_selected_year"] = year
                self.parent.save_config()
        
        super().accept()